<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Control extends CI_Controller {
	public function get(){
		$type = $this->input->get('type');
		$name = $this->input->get('name');
		$res = $this->db->get_where($type, array('name' => $name))->result_array()[0];
		unset($res['id']);
		unset($res['name']);
		echo json_encode(array('device' => $name,'attributes' => $res));
	}

	public function set(){
		$type = $this->input->get('type');
		$name = $this->input->get('name');
		$token = $this->input->get('token');
		//$post = $GLOBALS['HTTP_RAW_POST_DATA'];
		$post = file_get_contents("php://input");
		$res = $this->db->get_where('users',array('token'=>$token))->result_array()[0];
		if ($res == NULL) {
			echo json_encode(array('status'=>'failed','info'=>'invalid_token'));
		}elseif((time()-strtotime($res['update']))>3600){
			echo json_encode(array('status'=>'failed','info'=>'time_out'));
		}else{
			$request = json_decode($post,true);
			//var_dump(json_encode(array('device'=>'player','attribute'=>array('status'=>'stop'))));
			if ($request != NULL){
				if($request['attribute'] != NULL){
					$this->db->update($type, $request['attribute'], array('name' => $name));
					$res = $this->db->get_where($type, array('name' => $name))->result_array()[0];
					unset($res['id']);
					unset($res['name']);
					echo json_encode(array('device' => $name,'attributes' => $res));
					exit;
				}
				echo json_encode(array('device' => $name,'attributes' => $res));
			}
		}	
	}
}

?>